﻿using System.Web.Mvc;
using System.Web.Security;
using CodeContrib.Web.Mvc;
using CodeContribBlog.Data;
using CodeContribBlog.Web.Mvc.Models;

namespace CodeContribBlog.Web.Mvc.Controllers
{
	public class SecurityController : Controller
	{
		private readonly BlogContext _blogContext;

		public SecurityController()
		{
			_blogContext = new BlogContext();
		}

		//[HttpPost]
		//[ValidateAntiForgeryToken]
		public ActionResult LogOut(string returnUrl)
		{
			FormsAuthentication.SignOut();

			return RedirectFromLoginPage(returnUrl);
		}

		public ActionResult Login()
		{
			return View("Login", new LoginModel());
		}

		[HttpPost]
		[ExportModelStateToTempData]
		[ValidateAntiForgeryToken]
		public ActionResult Login(LoginModel viewModel, string returnUrl)
		{
			var password = viewModel.Password;
			viewModel.Password = null;

			if (!ModelState.IsValid)
			{
				return View("Login", viewModel);
			}

			var user = _blogContext.Users.FindByEmailAddress(viewModel.EmailAddress);

			if (user == null
			    || !user.ValidatePassword(password))
			{
				ModelState.AddModelError("__FORM", "The username and password do not match. Please try again.");

				return View("Login", viewModel);
			}

			FormsAuthentication.SetAuthCookie(viewModel.EmailAddress, viewModel.RememberMe);

			return RedirectFromLoginPage(returnUrl);
		}

		private ActionResult RedirectFromLoginPage(string returnUrl = null)
		{
			return (string.IsNullOrEmpty(returnUrl)) ? RedirectToRoute("Home") : (ActionResult)Redirect(returnUrl);
		}
	}
}